#include <QApplication>
#include <QDialog>
#include <QObject>
#include "ui_dialog.h"
#include "controller.h"
#include <QLabel>

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

char* getFileContent(char* filename){
	FILE* f=fopen(filename,"r");
	if(f!=NULL){
		char* buffer=(char*)malloc(1024*10);
		int n=fread(buffer,1,1024*10,f);
		buffer[n]=0;
		fclose(f);
		return buffer;
	}
	return NULL;
}


void Controller::print(){
	char* buffer=getFileContent("/Users/Liq/Desktop/ref/php_manual/about.prototypes.html");
	if(buffer!=NULL){
		ui->tb->setText(QString(buffer));
	}else{
		ui->tb->setText("hello from button");
	}
	
}

void Controller::testListWidget(){
	//ui->listWidget->addItem(tr("hello"));
	QListWidget* lw=ui->listWidget;
	
	char path[]="/Users/Liq/Desktop/ref/php_manual";
	basepath=new QString(path);
	
	DIR* dir=opendir(path);
	if(dir!=NULL){
		char* file;
		struct dirent* de;
		while(NULL!=(de=readdir(dir))){
			char* fn=de->d_name;
			if(strcmp(fn,".") !=0 && strcmp(fn,"..")!=0)
				lw->addItem(QString(de->d_name));
		}
		closedir(dir);
	}
}


void Controller::itemClicked(QListWidgetItem* item){
	ui->textBrowser->setText("loading ");
	QString nf=*basepath;
	nf.append("/");
	nf.append(QString(item->text()));
	ui->textBrowser->setText(nf);
	
	char* data=getFileContent(nf.toAscii().data());
	if(data!=NULL)
		ui->textBrowser->setHtml(QString(data));
}


int main(int argc, char *argv[])
{
	
    QApplication app(argc, argv);
    Ui_Dialog *ui = new Ui_Dialog;
	Controller ctrl(ui);
	QDialog *dialog=new QDialog;
	ui->setupUi(dialog);
	
	//MovieWidget* mw=new MovieWidget(dialog);
	//ui->vboxLayout2->addWidget(mw);
	
	
	dialog->layout();//->setSizeConstraint(QLayout::SetFixedSize);
	
	
	
	QString str=QString::fromUtf8("hello 中文");
	ui->tb->setText(str);
	
	QObject::connect(ui->pushButton,SIGNAL(clicked()),&ctrl,SLOT(print()));
	
	QObject::connect(ui->pushButton,SIGNAL(clicked()),&ctrl,SLOT(testListWidget()));
	QObject::connect(ui->pushButton,SIGNAL(clicked()),&ctrl,SLOT(testTextBrowser()));
	
	QObject::connect(ui->listWidget,SIGNAL(itemClicked(QListWidgetItem*))
		,&ctrl,SLOT(itemClicked(QListWidgetItem*)));
    dialog->show();
    return app.exec();
}